import Singleton from "./Singleton";
import GameConfig from "./GameConfig"
import BaseView from "./BaseView"
import BaseApp from "./BaseApp";
import { sys,Node, Button, UITransform, Prefab, instantiate } from "cc";
import { bundleTool } from "./bundleTool";

const KEY_ROR_SAVE:string = "guides_finish"  // 本地变量名--另外GuideMgr须有common/guideNode的prefab

export default class GuideMgr extends Singleton {
	private _isGuide:boolean = true;

	private _curStepIndex:number = 0;

	private _guideCfgs = null;

	private _guideFinish =[];

	private _curGuideCfg = null;

	private _callback = null;

	private _callTarget = null;

	constructor() {
		super();
	}

	cleanup():void {
		this._guideCfgs = null;
		this._guideFinish = null;
		this._curGuideCfg = null;
		this._callback = null; 
		this._callTarget = null;
	}

	checkAllFinish():boolean {
		if(this._guideFinish.length>= this._guideCfgs.length){
			this._isGuide = false;
			this.cleanup();
			GameConfig.instance().cleanTable("guides")

			return true;
		}

		return false;
	}

	setIsGuide(isGuide:boolean):void{
		this._isGuide = isGuide;
		if(this._isGuide){
			this._guideCfgs = GameConfig.instance().getTable("guides");
			const str = sys.localStorage.getItem(KEY_ROR_SAVE);

			if (str !== null && str !== "") {
				this._guideFinish = JSON.parse(str);
				if( this.checkAllFinish()) return ;
				for(let i = 0; i<this._guideFinish.length; i++) {
					const v = this._guideFinish[i];

					this._guideCfgs[v].finished = true;
				}
			}else{
				this._guideFinish = [];
			}
		}else{
			this.cleanup();
		}
	}

	private _saveFinishedInf(guidix:number):void{
		this._guideCfgs[guidix].finished = true;
		this._guideFinish.push(guidix);
		sys.localStorage.setItem(KEY_ROR_SAVE,JSON.stringify(this._guideFinish));
		this.checkAllFinish();
	}

	private _updateGuide(viewBase:BaseView,isCheck:boolean):void{
		if(! this._curGuideCfg) return;
		const step =this._curGuideCfg.steps[this._curStepIndex];
		let guideView:Node|null = null;

		if(isCheck){
			if(viewBase.node==null||viewBase.node.name!=step.view)
			{
				viewBase = BaseApp.instance().getViewByName(step.view);
				if(viewBase==null) {
					console.log("click to skip, no view for :"+JSON.stringify(step));

					return;
				}
			}
		}

		this._callTarget =viewBase.node.getChildByPath(step.target);
		this._callback = viewBase[step.targetCallback]
		guideView =viewBase.node.getChildByPath("touchNode/guideView")
		if(guideView==null){
			bundleTool.instance().loadAsyncFromBundle("common", "guideNode",Prefab).then((prefab:Prefab) => {
				if (prefab == null) {
					console.log("路径错误..");

					return;
				}

				const touchNode = instantiate(prefab);

				touchNode.name = "touchNode";
				const call= (event):void=>{
					if (this._callback!=null) {             
						this._callback.call(viewBase,this._callTarget.getComponent(Button));
					}

					this._curStepIndex = this._curStepIndex+1
					if(this._curStepIndex >= this._curGuideCfg.steps.length){
						touchNode.active = false;
						touchNode.pauseSystemEvents(true);
						this._saveFinishedInf(this._curGuideCfg.id)
						this._curStepIndex =0;
						this._curGuideCfg = null;
					}else{
						this._updateGuide(viewBase,true);
					}
				};

				touchNode.on(Node.EventType.TOUCH_START,call,this);
				guideView = touchNode.getChildByName("guideView");

				const guideContent = guideView.getChildByName("guideContent");

				guideContent.on(Node.EventType.TOUCH_START,()=>{console.log("xxxxxxxxx")});
				touchNode.parent = viewBase.node;
				touchNode.resumeSystemEvents(true);
				touchNode.active = true;
				guideView.addComponent(UITransform).setContentSize( this._callTarget.getComponent(UITransform).contentSize);
				guideView.setWorldPosition ( this._callTarget.worldPosition );
			},(reason:string) => {
				console.error(reason);
			})
		}
		else{
			guideView.parent.resumeSystemEvents(true);
			guideView.parent.active = true;
			guideView.addComponent(UITransform).setContentSize( this._callTarget.getComponent(UITransform).contentSize);
			guideView.setWorldPosition ( this._callTarget.worldPosition );  // 本地坐标是不一样的，应该设置世界坐标
		}
	}

	checkAndGuide(viewBase:BaseView):void{
		if(! this._isGuide||!this._guideCfgs) return;
		for(let i = 0; i<this._guideCfgs.length; i++) {
			const v = this._guideCfgs[i];

			if(v.finished!= true&& v.steps[0].view==viewBase.node.name) {
				this._curStepIndex =0;
				this._curGuideCfg = v;
				break;
			}
		}

		this._updateGuide(viewBase,false);
	}
}